#############################################################################
#  Copyright (C) 2007 Boscovich, Maximiliano - mboscovich@gmail.com          #
#                                                                            #
#  This program is free software; you can redistribute it and/or modify      #
#  it under the terms of the GNU General Public License as published by      #
#  the Free Software Foundation; either version 3 of the License, or         #
#  (at your option) any later version. See tht GPL_Licence.txt for details.  #
#                                                                            #

#  This program is distributed in the hope that it will be useful,           #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              #
#  GNU General Public License for more details.                              #
#                                                                            #
##############################################################################

import apt_pkg, sys, time
sys.path.append("../")

from sqlobject import dberrors
from PyQt4 import QtGui, QtCore
from tables import Package

class packages:
    
    packageslist = []
    packageslist_by_name = []
    def packagesToList(self,packages):
        list = []
        for package in packages:
            list.append(package.Name)
        return list
    
    def getAptCache(self):
        self.__class__.message.setLabelText("Consultando la lista de paquetes de APT")
        self.__class__.message.setValue(30)
        time.sleep(0.1)
        apt_pkg.init()
        self.__class__.message.setValue(40)
        time.sleep(0.1)
        cache = apt_pkg.GetCache().Packages
        return cache
        
    
    def getDbPackagesList(self,order=None):
        if order == 'order':
            list = self.packagesToList(Package.select(orderBy="Name"))
            return list
        else:
            list = self.packagesToList(Package.select())
            return list

    def getNewPackagesAvaible(self):
        self.__class__.message = QtGui.QProgressDialog("cargando informacion de paquetes","Cancelar",0,4)
        self.__class__.message.setWindowModality(QtCore.Qt.WindowModal)
        self.__class__.message.forceShow()
        self.__class__.message.setValue(0)
        time.sleep(0.1)                                      
        self.__class__.message.setLabelText("Chequeando si hay paquetes nuevos para cargar....")
        self.__class__.message.setValue(1)
        time.sleep(0.1)
        self.loadPackagesFromApt()
        packagesOnDB=self.getDbPackagesList()
        newPackages=[]
        for package in self.packageslist_by_name:
            if package not in packagesOnDB:
                newPackages.append(package)
        return newPackages

    def loadNewPackagesToDb(self,newPackages):
        self.__class__.message.setLabelText("Cargando en la base de datos (puede demorar unos minutos, sea paciente) ...")
        self.__class__.message.setValue(3)
        time.sleep(0.1)

        # FIXME: chequear como hace los insert en la base, para ver si se puede mejorar el 
        # rendimiento. Por ahi esta haciendo una transaccion en cada insert, y se puede sacar

        for package in newPackages:
            try:
                new_package=Package(Name=package)
            except dberrors,error:
                print error

    def loadPackagesFromApt(self):
        for package in self.getAptCache():
            self.__class__.packageslist_by_name.append( package.Name )
    
    def listAll(self):
        return self.getDbPackagesList('order')

    def load_package_on_widget(self,widget):
        widget.reset()
        for package in self.__class__.packageslist_by_name:
            widget.addItem(package)

    def refreshPackagesAvaible(self):
        newPackages=self.getNewPackagesAvaible()
        self.__class__.message.setValue(2)
        if len(newPackages)>0:
            self.loadNewPackagesToDb(newPackages)
        self.__class__.message.setLabelText("Listo!")
        self.__class__.message.setValue(4)
        del(self.__class__.message)
